# 单层列表转化函数，json_array列表，field_mappings是一个字典结构，{“源字段”:“目标字段”}
# def extract_and_rename_fields_from_array(json_array, field_mappings):
#     extracted_array = []
#     for item in json_array:
#         extracted_item = {}
#         for source_field, target_field in field_mappings.items():
#             extracted_item[target_field] = item[source_field]
#         extracted_array.append(extracted_item)
#     return extracted_array


# 改进版
json_array = [
    {
        "a":"01",
        "b":3,
        "c":4
    },
    {
        "a":"05",
        "b":65,
        "c":666
    }
]
field_mappings = {"a":"num","b":"age","d":"name"}
def extract_and_rename_fields_from_array(json_array, field_mappings):
    extracted_array = []
    for item in json_array:
        extracted_item = {}
        for source_field, target_field in field_mappings.items():
            if source_field in item:
                extracted_item[target_field] = item[source_field]
            else:
                extracted_item[target_field] = ""
        extracted_array.append(extracted_item)
    return extracted_array

print(extract_and_rename_fields_from_array(json_array,field_mappings))

# 时间戳转时间文本函数
import time
def timestamp_to_datetime(timestamp):
    try:
        time_struct = time.localtime(timestamp)
        datetime_text = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)
        return datetime_text
    except Exception as e:
        print('发生错误:', str(e))
        return None


'''
3.时间文本转时间戳函数
'''
import time


def datetime_to_timestamp(datetime_text):
    try:
        time_struct = time.strptime(datetime_text, '%Y-%m-%d %H:%M:%S')
        timestamp = time.mktime(time_struct)
        return int(timestamp)
    except Exception as e:
        print('发生错误:', str(e))
        return None


'''
4.二维列表转换位具有指定键的字典对象：，keys =  ["FName", "FNumber"] 是这种形式
标签：金蝶
'''


def convert_to_objects(data, keys):
    obj_list = []
    for item in data:
        obj = dict(zip(keys, item))
        obj_list.append(obj)
    return obj_list


'''
5.截取指定标识符前面的字符串截取函数
'''


def extract_string(string, delimiter='-'):
    index = string.find(delimiter)  # 找到指定分隔符的索引
    if index != -1:
        return string[:index]  # 使用切片截取分隔符之前的部分
    else:
        return string  # 如果找不到分隔符，返回原字符串


# 获取当前日期，格式为：'2023-08-24T00:00:00.00'

from datetime import datetime


def get_current_date():
    current_date = datetime.now().strftime("%Y-%m-%d")
    return current_date + "T00:00:00"



# 13位时间戳转换为日期时间文本
import datetime
def timestamp_to_datetime(timestamp):
    dt = datetime.datetime.fromtimestamp(timestamp / 1000.0)
    formatted_datetime = dt.strftime('%Y-%m-%d %H:%M:%S')
    return formatted_datetime


# 8.获取当前日期和下一天日期，时间为空函数
def get_date():
    from datetime import date, timedelta
    current_date = date.today()
    next_date = current_date + timedelta(days=1)
    return current_date, next_date


# 8.获取当前日期和下一天日期，时间为空函数
def get_datetime():
    from datetime import date, timedelta
    current_date = date.today()
    next_date = current_date + timedelta(days=1)
    return current_date, next_date


# 9.获取当前日期时间和下一天日期时间，时间格式化'2023-08-24 00:00:00.00'

def get_current_datetime():
    # 函数引用
    from datetime import date, timedelta, datetime
    # 获取当前日期
    current_date = date.today()
    # 获取下一天日期
    next_date = current_date + timedelta(days=1)
    # 拼接当前日期时间
    current_date_time = current_date.strftime("%Y-%m-%d") + " 00:00:00"
    # 拼接下一天日期时间
    next_date_time = next_date.strftime("%Y-%m-%d") + " 00:00:00"

    return current_date_time, next_date_time


# 10.生成递增页码列表
def get_page(star_page, end_page):
    page_size_list = []
    for i in range(star_page, end_page):
        page_size_list.append(i)
    return page_size_list



# 11.金蝶页码递增器
def get_kd_page(page_size, limit):
    page_size_list = []
    for i in range(0, page_size):
        StartRow = i * limit
        TopRowCount = (i + 1) * limit
        page = {"StartRow": StartRow, "TopRowCount": TopRowCount}
        page_size_list.append(i)
    return page_size_list

# 11.金蝶页码递增器
def get_kd_page1(page_size,limit):
    page_size_list = []
    for i in range(0, page_size):
        StartRow = i*limit
        TopRowCount = (i+1)*limit
        page = {"StartRow":StartRow,"TopRowCount":TopRowCount}
        page_size_list.append(page)
    return page_size_list


# 12.获取当前日期13位时间戳
def get_today_stamp():
    from datetime import date
    import time
    current_date = date.today()
    current_date_stamp = int(time.mktime(current_date.timetuple()) * 1000)
    return current_date_stamp


# 13.分组求和函数
# data是要分组求和的列表套字典数据，data是要分组求和的列表套字典数据，group_keys是一个元组，表示要根据哪些键进行分组,sum_keys参数传递了一个元组，其中包含了要进行求和的键。
def groupby_sum(data, group_keys, sum_keys):
    from itertools import groupby
    from operator import itemgetter
    data.sort(key=itemgetter(*group_keys))  # 先根据指定的键进行排序# 使用 groupby 对多个键进行分组，并对每个分组的值进行求和
    result_sum = []
    for key, group in groupby(data, key=itemgetter(*group_keys)):
        totals = {}
        for sum_key in sum_keys:
            total = sum(float(item[sum_key]) for item in group if item[sum_key].isdigit())
            totals[sum_key] = total
        result_sum.append(dict(list(zip(group_keys, key)) + list(totals.items())))
    return result_sum


# 14.列表分组函数（这个待议）
def group_by_keys(data, keys):
    from itertools import groupby
    # 按照键进行排序
    data.sort(key=lambda x: [x[key] for key in keys])
    # 使用groupby进行分组
    grouped_data = []
    for key, group in groupby(data, key=lambda x: [x[key] for key in keys]):
        grouped_data.append(list(group))
    return grouped_data


# 15.分组函数（这是对的）
from collections import defaultdict
from operator import itemgetter


def group_by_fields(data_list, *fields):
    result_group = defaultdict(list)
    for item in data_list:
        key = itemgetter(*fields)(item)
        key_str = '-'.join(map(str, key))
        result_group[key_str].append(item)
    return dict(result_group).values()


# 日期时间计算函数，start_time起始日期，days时长
from datetime import datetime, timedelta
def add_days(start_time, days):
    start_date = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
    new_date = start_date + timedelta(days=days)
    new_time = new_date.strftime("%Y-%m-%d %H:%M:%S")
    return new_time

# 文本类型日期时间和当前日期时间比较函数
def compare_datetime(date_time_str):
    from datetime import datetime
    current_datetime = datetime.now()
    date_time = datetime.strptime(date_time_str, "%Y-%m-%d %H:%M:%S")
    if current_datetime > date_time:
        return True
    else:
        return False

def temple():
    import datetime

    now = datetime.datetime.now()

    # 将当前时间转换为指定格式的字符串
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")

    print("当前时间为：", formatted_time)

def datestring_to_dateonly_10(date_string):
# 时间转化函数
    datetime_object = datetime.strptime(date_string, "%Y-%m-%d")
    date_only = datetime_object.date()
    return date_only

if __name__ == '__main__':
    s = "2023-10-03 12:09:56"
    print(s[0:10])
#
